package com.example.administrator.netdemo.network.gsonConverter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.jiongbull.jlog.JLog;

import java.io.IOException;
import java.io.StringReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;


/**
 * Creator: tsung_lin
 * data: 06/07/2017 10:21 AM
 * Description:
 */

public class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    public MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        //上传图片接口返回的结果不是base64编码的
        String result = value.string();
        JLog.e("接口返回数据：" + result);
//        if (isBase64(result)) {
//            //Base64解码
//            result = new String(Base64.decode(result, Base64.DEFAULT));
//        }
//        JLog.d(result);
        JsonReader jsonReader = gson.newJsonReader(new StringReader(result));
        jsonReader.setLenient(true);
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
//
//    /**
//     * 判断是否为Base64加密
//     */
//    public static boolean isBase64(String result) throws IOException {
//        String decodeStr = new String(Base64.decode(result, Base64.DEFAULT));
//        String codingStr = Base64.encodeToString(decodeStr.getBytes(), Base64.NO_WRAP);
//        if (result.equals(codingStr)) {
//            return true;
//        }
//        return false;
//    }
}
